import { GetAllUserDashboard, SetDashboardMenuShow, GetReportListData } from 'services/home';
import { config } from 'utils';

export default {
  namespace: 'home',
  state: {
    sdbVisible: false,
    allDashboard: [],
    dashboardList: [],
    reportDatas: {}, // 通过报表id保存 报表数据
    searchValue: '',
    currentTabsNum: 0,
    refreshing: false,
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        setTimeout(() => {
          // window.history.go(-1)
          // if (window.plus) {
          //   alert(1)
          // } else {
          //   alert(2)
          // }
        }, 2000);
        if (location.pathname === '/') {
          setTimeout(() => {
            dispatch({ type: 'initeData' });
          }, 100);
        }
      });
    },
  },
  effects: {
    // 改变state
    *changeState({ payload }, { put }) {
      yield put({ type: 'updateState', payload });
    },
    // 初始化
    *initeData(_, { put }) {
      yield put({ type: 'loadDbList' });
    },
    // 加载 Dashboard
    *loadDbList(_, { put, call }) {
      const data = yield call(GetAllUserDashboard);

      yield put({ type: 'setDbList', payload: data });
    },
    // 组装 dashboardList
    *setDbList({ payload }, { put, call, select }) {
      // 找到 首页仪表盘和 菜单仪表盘 并存入state
      let homePageBashboard = {};
      const menuDashboard = [];

      const bigScreen = [];
      // 不含报表的仪表盘
      for (const board of payload) {
        if (!board || !board.DID || !board.Dashboard) {
          // 如果该仪表盘为空就跳过
          continue;
        }
        const { Dashboard = {}, IsMenuShow, IsHomePageShow } = board;
        if (IsHomePageShow) {
          homePageBashboard = Dashboard;
          homePageBashboard.Name = '首页';
          homePageBashboard.title = '首页';
        } else if (IsMenuShow) {
          Dashboard.title = Dashboard.Name;
          // 内置的大屏仪表盘的类型 排在前面
          
          config.bigScreenCategoryID.includes(Dashboard.CategoryID)
            ? bigScreen.push(Dashboard)
            : menuDashboard.push(Dashboard);
        }
      }
      // 有首页就加首页
      const dashboardList = homePageBashboard.ID
        ? [...bigScreen, homePageBashboard, ...menuDashboard]
        : [...bigScreen, ...menuDashboard];
      yield put({
        type: 'updateState',
        payload: {
          dashboardList,
          allDashboard: payload,
        },
      });
      // 获取报表数据
      yield dashboardList && dashboardList.length && put({ type: 'getReportData' });
    },

    // 根据报表ids获取 报表数据
    *getReportData({ payload = {} }, { put, call, select }) {
      yield put({ type: 'updateState', payload: { refreshing: true } });

      const { dashboardList, currentTabsNum } = yield select(_ => _.home);
      // 选中的仪表盘id
      let { currentTabsNum: newCurrentTabsNum = currentTabsNum } = payload;
      // 选中的仪表盘
      let currentDashboard = dashboardList[newCurrentTabsNum];

      let ReportList = [];
      try {
        ReportList = JSON.parse(currentDashboard.BlockRelateReport);
      } catch (e) {}
      const ReportIds = new Set();
      for (const report of ReportList) {
        report.reporterId && ReportIds.add(report.reporterId);
      }
      // 获取新报表数据
      const newReportList = yield call(GetReportListData, Array.from(ReportIds));
      const addReportDatas = newReportList.reduce((obj, item) => {
        if (item.ID && item.DataJson) {
          obj[item.ID] = item;
        }
        return obj;
      }, {});

      yield put({
        type: 'updateReportDatas',
        payload: {
          currentTabsNum: newCurrentTabsNum,
          reportDatas: addReportDatas,
          refreshing: false,
        },
      });
    },

    // 改变 Dashboard
    *changeDbList({ payload }, { put, call, select }) {
      if (payload.length) {
        const { allDashboard } = yield select(_ => _.home);
        const newAllDashboard = allDashboard.map(DB => {
          const changeDB = payload.find(e => e.ID === DB.ID);
          return changeDB ? { ...DB, ...changeDB } : DB;
        });
        yield call(SetDashboardMenuShow, payload);
        yield put({ type: 'setDbList', payload: newAllDashboard });
      }
      yield put({
        type: 'updateState',
        payload: { sdbVisible: false },
      });
    },
  },
  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 设置 当前仪表盘及其报表数据
    updateReportDatas(state, { payload }) {
      const { reportDatas, currentTabsNum = 0 } = payload;
      return {
        ...state,
        currentTabsNum,
        reportDatas: {
          ...state.reportDatas,
          ...reportDatas,
        },
        refreshing: false,
      };
    },
  },
};
